package org.nf.web.view;

import com.google.gson.GsonBuilder;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;
import org.nf.web.servlet.ServletApi;
import org.nf.web.servlet.View;

import java.io.IOException;

/**
 * @Author czl
 * @Date 2024-05-20
 * Json视图，将对象转换为Json
 */
public class JsonView implements View {

    private final Object object;

    private final GsonBuilder builder;


    public JsonView(Object object){
        this.object = object;
        builder = new GsonBuilder();
    }

    /**
     * 格式化日期
     * @param pattern 日期格式
     */
    public void format(String pattern){
        builder.setDateFormat(pattern);
    }



    @Override
    public void render(ServletApi api) throws ServletException, IOException {
        String json = builder.create().toJson(object);
        HttpServletResponse response = api.response();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);
    }
}
